<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoles">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 渲染角色列表 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- <pre>{{scope.row}}</pre> -->
            <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id"
              :class="['bdbottom',i1 === 0?'bdtop':'','vcenter']">
              <!-- 一级权限的显示 -->
              <el-col :span="5">

                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限的显示 -->
              <el-col :span="19">
                <!-- 通过for循环来 渲染出2级权限 (第0个无需显示border-top)-->
                <el-row :class="[i2===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3,i3) in item2.children" :key="item3.id" closable
                      @close="removeRightById(scope.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>

              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操做" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑
            </el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeRolesById(scope.row.id)">删除
            </el-button>
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--添加角色的对话框 -->
    <el-dialog :visible.sync="addDialogVisible" title="添加角色" width="50%" @close="addDialogClosed">
      <el-form label-width="90px" ref="addFormRef" :model="addForm" :rules="editFormRules">
        <el-form-item label="角色名称" prop="roleName" class="yiHang">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" class="yiHang">
          <el-input type="textarea" rows="2" v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addRoleInfo">确定</el-button>
      </div>
    </el-dialog>

    <!--修改角色的对话框 -->
    <el-dialog :visible.sync="editDialogVisible" title="修改角色" width="50%" @close="editDialogClosed">
      <el-form label-width="90px" ref="editFormRef" :model="editForm" :rules="editFormRules">
        <el-form-item label="角色名称" prop="roleName" class="yiHang">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" class="yiHang">
          <el-input type="textarea" rows="2" v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="eidtRoleInfo">确定</el-button>
      </div>
    </el-dialog>

    <!--分配权限的Dialog -->
    <el-dialog title="分配权限" width="50%" :visible.sync="setRightDialogVisible" @close="setRightDialogClosed">
      <!-- 树形控件-->
      <el-tree :data="rightslist" show-checkbox :props="treeProps" node-key="id" :default-expand-all="true"
        :default-checked-keys="defKeys" ref="treeRef">
      </el-tree>

      <div slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="allotRights">确定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  // !注:添加角色 编辑角色 删除角色没做
  export default {
    data() {
      return {
        // 所有角色的列表数据
        rolelist: [],
        // 控制添加角色对话框的显示与隐藏
        addDialogVisible: false,
        // 控制修改角色对话框的显示与隐藏
        editDialogVisible: false,
        // 查询到需要修改的用户的信息
        editForm: {},
        // 需要修改的用户规则对象
        editFormRules: {
          roleName: [{
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          }, {
            min: 2,
            max: 15,
            message: '字符长度在2~15之间',
            trigger: 'blur'
          }],
          roleDesc: [{
            required: true,
            message: '请输入角色描述',
            trigger: 'blur'
          }, {
            min: 2,
            max: 30,
            message: '字符长度在2~30之间',
            trigger: 'blur'
          }]

        },
        addForm: {
          roleName: '',
          roleDesc: ''
        },
        // 控制分配权限对话框的显示与隐藏
        setRightDialogVisible: false,
        // 所有的权限列表数据
        rightslist: [],
        // 树形控件的属性绑定对象
        treeProps: {
          label: 'authName',
          children: 'children'
        },
        // 默认需要勾选的id节点的数组
        defKeys: [],
        // 获取即将要被分配角色的角色id
        roleId: ''
      }
    },
    methods: {
      async getRolesList() {
        const {
          data: res
        } = await this.$http.get('roles')
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
        this.rolelist = res.data
      },
      // 添加角色对话框显示
      addRoles() {
        this.addDialogVisible = true
      },
      // 关闭添加角色对话框时
      addDialogClosed() {
        this.$refs.addFormRef.resetFields()
      },
      // 发送请求添加角色信息
      async addRoleInfo() {
        this.$refs.addFormRef.validate((isRightBoolean, obj) => {
          if (!isRightBoolean) return this.message.error('添加角色失败!')
        })

        const {
          data: res
        } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message({
            type: 'error',
            message: '添加角色失败!',
            duration: 1200
          })
        }
        this.addDialogVisible = false
        this.getRolesList()
        this.$message.success('角色添加成功')
      },
      // 根据Id删除对应的权限
      async removeRightById(role, rightId) {
        // 弹框提示是否要删除
        const confirmResult = await this.$confirm('此操作将永久删除该角色的这个权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => error)
        if (confirmResult !== 'confirm') {
          return this.$message({
            type: 'info',
            message: '取消了删除！',
            duration: 1500
          })
        }
        const {
          data: res
        } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status !== 200) return this.$message.error('删除权限失败！')
        // this.getRolesList() 这样写就要重新渲染整个table 我们删完后服务器会返回当前这个id的最新的数据 也就是res.data
        role.children = res.data
      },

      // 根据Id删除对应的角色
      async removeRolesById(roleId) {
        // console.log(roleId)
        const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => {
          return error
        })

        if (confirmResult !== 'confirm') {
          return this.$message.info('已经取消删除')
        }

        const {
          data: res
        } = await this.$http.delete('roles/' + roleId)
        if (res.meta.status !== 200) return this.$message.error('删除角色失败')
        this.$message.success('删除角色成功')
        this.getRolesList()
      },
      async showEditDialog(roleId) {
        console.log(roleId)
        this.editDialogVisible = true
        const {
          data: res
        } = await this.$http.get('roles/' + roleId)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.editForm = res.data
      },
      // 监听修改角色信息对话框的关闭事件
      editDialogClosed() {
        this.$refs.editFormRef.resetFields()
      },
      // 根据id修改角色信息
      async eidtRoleInfo() {
        // validate方法并传入两个参数：是否校验成功和未通过校验的字段
        this.$refs.editFormRef.validate((isOkBoolean, obj) => {
          console.log(isOkBoolean)
          if (!isOkBoolean) return this.$message.error('角色信息未通过验证')
        })
        // 发起角色修改
        const {
          data: res
        } = await this.$http.put('roles/' + this.editForm.roleId, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        })

        if (res.meta.status !== 200) {
          return this.$message.error('更新角色信息失败')
        }

        this.editDialogVisible = false
        this.getRolesList()
        this.$message.success('更新角色信息成功')
      },
      // 分配权限的Dialog框
      async showSetRightDialog(role) {
        this.roleId = role.id
        const {
          data: res
        } = await this.$http.get('rights/tree')
        if (res.meta.status !== 200) return this.$message.error('获取权限数据失败')
        // 获取所有权限列表数据保存到data中
        this.rightslist = res.data
        console.log(this.rightslist)

        // 递归获取三级节点的id
        this.getLeafKeys(role, this.defKeys)
        this.setRightDialogVisible = true
      },
      // 通过递归的形式 获取角色下所有三级的id 保存到数组defKeys中
      getLeafKeys(node, arr) {
        if (!node.children) {
          return arr.push(node.id)
        }

        node.children.forEach(item => {
          this.getLeafKeys(item, arr)
        })
      },
      // 监听分配权限对话框的关闭事件
      setRightDialogClosed() {
        this.defKeys = []
      },
      // 点击为角色分配权限
      async allotRights() {
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        // console.log(keys)
        const idStr = keys.join(',')

        const {
          data: res
        } = await this.$http.post(`roles/${this.roleId}/rights`, {
          rids: idStr
        })
        if (res.meta.status !== 200) return this.$message.error('分配权限失败')
        this.getRolesList()
        this.setRightDialogVisible = false
        this.$message.success('分配权限成功')
      }
    },
    created() {
      this.getRolesList()
    }
  }

</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  // 纵向居中对齐样式
  .vcenter {
    display: flex;
    align-items: center;
  }

  // 设置字体大小
  .el-form-item .el-textarea {
    font-size: 15px;
    font-weight: 555;
  }

  // 在一行上显示
  .yiHang {
    white-space: nowrap;
  }

</style>
